// pages/find_info/index.js
var t = getApp(),
  e = t.requirejs("api/index"),
  core = t.requirejs("core"),
  wxParse = t.requirejs("wxParse/wxParse");

Page({
  data: {
    route: "find_info",
    menu: t.tabBar,
    menu_show: false,
    show: false,
    use_wxParse:true,
    dobuy:false,
    page:1,
    now_sku:{},
    num:1,
    nowprice:0.00,
    skus:[],
    isinputing:false,
    isvip: true,
    samegroup:[],
    loaded:false,
    liked:false,
    isplay:false,
    duration:0,
    currecttime:0,
    timechanging:false,
    nowtime:"00:00",
    endtime:"00:00",
  },
  //底部导航跳转
  menu_url: function (k) {
    core.menu_url(k, 2);
  },
  onLoad: function (options) {
    var that=this;
    getApp().getExtC(function () {
    if (options != null && options != undefined) {
      that.setData({
        tabbar_index: options.tabbar_index ? options.tabbar_index : -1
      });
    }
    core.setting();
      that.setData({
      menu: getApp().tabBar
    })
      var key = t.isInArray(getApp().tabBar.list, that.data.route);
    if (key) {
      that.setData({
        menu_show: true
      })

    }

      if (that.data.tabbar_index >= 0) {
      that.setData({
        showtabbar: true,
      })
    }
      that.setData({
      id: options.id
    })
      that.getinfo();
      that.getlist();
      that.getallprice();
    })
  },
  to_info:function(e){
    var that=this,
    id=core.pdata(e).id;
    if(id){
      that.setData({
        id: id,
        page:1,
        samegroup: []
      })
      that.getinfo();
      that.getlist();
      that.getallprice();
    }
    
  },
  inputing:function(e)
  {
    console.log(e);
    var isinputing = this.data.isinputing;
    console.log(isinputing);
    this.setData({
      isinputing: !isinputing
    })
  },

  dobuy:function(e)
  {
    if(this.data.skus.length > 0)
    {
      this.setData({
        dobuy: true
      })
    }
    else
    {
      core.alert("未添加资费,暂不可购买");
    }
  
  },

  hidebuy:function(e)
  {
    if (!this.data.isinputing)
    {
      this.setData({
        dobuy: false
      })
    }
  },

  choose_sku: function(e){

    console.log(e);
    var index = e.currentTarget.dataset.index;
    var sku = this.data.skus[index];

    var nowprice = (sku.price * this.data.num).toFixed(2);

    this.setData({
      now_sku: sku,
      nowprice: nowprice
    })

  },

  num_change: function(e){

    console.log(e);
    var num = e.detail.value;
    var nowprice = (this.data.now_sku.price * num).toFixed(2);
    this.setData({
      num: num,
      nowprice: nowprice
    })
  },


  tobuy:function(e)
  {

    if(this.data.num <= 0){
      core.error("购买数量必须大于0");
      return
    }

    this.setData({
      dobuy: false
    });

    core.loading("支付中...");
    var that = this;
    var data = {};
    data.content_id = this.data.detail.id;
    data.price_id = this.data.now_sku.id;
    data.num = this.data.num;
    data.uid = t.getCache('userinfo').uid;
    data.openid = t.getCache("userinfo").openid;

    core.get("paycontent/createOrder", data, function (t) {
      if (0 == t.code) {

        wx.requestPayment({
          'timeStamp': t.info.timeStamp,
          'nonceStr': t.info.nonceStr,
          'package': t.info.package,
          'signType': 'MD5',
          'paySign': t.info.paySign,
          'success': function (res) {

            console.log(res)
            if (res.errMsg == "requestPayment:ok") {

              wx.showToast({
                title: "支付成功！",
                icon: "success",
                duration: 2000,
              })

              that.setData({
                page:1
              })

              setTimeout(function(){
                that.getinfo();
                that.getlist();
                that.getallprice();
              },2000);

            } else {
              core.error('支付失败！');
            }
          },
          'fail': function (res) {
            core.error('您已经取消支付！')
          }
        })

      } else {
        core.error(t.msg)
      }
    });

  },

  play_music: function () {

    var that=this;
    var title = this.data.detail.title;
    var coverImgUrl = this.data.detail.image;
    var src = this.data.detail.audio_url;

    if (src && src != '') {
      const backgroundAudioManager = wx.getBackgroundAudioManager()
      backgroundAudioManager.title = title
      backgroundAudioManager.coverImgUrl = coverImgUrl
      backgroundAudioManager.src = src 
      this.setData({
        isplay:true
      });

      backgroundAudioManager.onCanplay(function(res){
        console.log("onCanplay !!!!!!!!!");
        that.setData({
          duration: parseInt(backgroundAudioManager.duration),
          endtime: that.timeformat(parseInt(backgroundAudioManager.duration))
        })
      })

      backgroundAudioManager.onPlay(function (res) {
        console.log("onPlay !!!!!!!!!");
        that.setData({
          duration: parseInt(backgroundAudioManager.duration),
          endtime: that.timeformat(parseInt(backgroundAudioManager.duration))
        })

        that.startAnimationInterval();
      })

      backgroundAudioManager.onEnded(function (res) {
        console.log("onEnded !!!!!!!!!");
        that.setData({
          currecttime:0,
          isplay: false,
          nowtime:"00:00"
        })
      })

      backgroundAudioManager.onPause(function (res) {
        console.log("onPause !!!!!!!!!");
        that.setData({
          isplay:false,
        })
      })

      backgroundAudioManager.onTimeUpdate(function (res) {

        console.log("onTimeUpdate !!!!!!!!!");

        if (!that.data.timechanging)
        {
          that.setData({
            currecttime: parseInt(backgroundAudioManager.currentTime),
            nowtime: that.timeformat(parseInt(backgroundAudioManager.currentTime))
          })
        }
       
      })

    }

  },

  timeformat:function(time)
  {
    var m = parseInt(time / 60);
    m = m < 10 ? "0"+m : ""+m;
    var s = time % 60;
    s = s < 10 ? "0" + s : "" + s;
    return m+":"+s;
  },

  timechanging:function(res)
  {
    this.setData({
      timechanging: true,
    })
  },

  timechange:function(res){

    console.log("timechange !!!!!!!!");

    var time = res.detail.value;
    wx.getBackgroundAudioManager().seek(time);
    this.setData({
      currecttime:time,
      timechanging:false,
    })

  },

  play_status_change :function()
  {
    if(this.data.isplay)
    {
      wx.getBackgroundAudioManager().pause();
      this.setData({
        isplay:false
      })
    }
    else
    {
      wx.getBackgroundAudioManager().play();
      this.setData({
        isplay: true
      })
    }
  },

  onShow: function () {
    this.checkuser();
  },

  checkuser: function () {
    var that = this;
    var e = {};
    core.get("paycontent/checkuser", {
      uid: t.getCache('userinfo').uid,
    }, function (t) {
      if (t.code == 0) {
        e.isvip = t.info;
        that.setData(e);
      } else {
        a.alert(t.msg);
      }
    }, true)
  },

  dolike:function()
  {
    var that = this;
    var e = {};
    core.get("paycontent/dolike", {
      id:that.data.detail.id,
      uid: t.getCache('userinfo').uid,
    }, function (t) {
      if (t.code == 1) {
        e.liked = !that.data.liked;
        that.setData(e);
      } else {
        a.alert("收藏失败");
      }
    }, true)
  },

  getinfo:function(){

    var a = this,
      id = a.data.id;

    var e = {};
    core.get("paycontent/paycontent_info", {
      id: id,
      uid: t.getCache('userinfo').uid,
    }, function (t) {
      wx.setNavigationBarTitle({
        title: t.info.title ? decodeURIComponent(t.info.title) : '产品详情'
      })
      if (t.code == 0) {

        try {
          wxParse.wxParse("wxParseData", "html", t.info.content, a, "0");
          e.use_wxParse = true;
          console.log("use wxParse !!!");
        }
        catch (err) {
          e.use_wxParse = false;
          console.log("not use wxParse !!!");
        }

        e.detail = t.info;
        e.liked = t.info.liked;
        e.show = true;
        a.setData(e)
        if (t.info.paycontent_type == 1) {
          a.play_music();
        }
      } else {
        core.alert(t.msg)
      }
    }, true)

  },


  getlist: function () {
    var a = this,id = a.data.id;
    var e = {};
    core.get("paycontent/samegroup", {
      id: id,
      uid: t.getCache('userinfo').uid,
      page: a.data.page,
    }, function (t) {
      if (t.code == 0) {
      
        if(t.info.length > 0)
        {
          if (a.data.page == 1)
          {
            e.samegroup = t.info;
          }
          else
          {
            e.samegroup = a.data.samegroup.concat(t.info);
          }
          
          e.page = a.data.page+1;
        }
        else
        {
          e.loaded = true
        }

        a.setData(e);
      } else {
        core.alert(t.msg)
      }
    }, true)
  },

  getallprice: function () {
    var a = this, id = a.data.id;
    var e = {};
    core.get("paycontent/allprice", {
      id: id,
    }, function (t) {
      if (t.code == 0) {

        if (t.info.length > 0)
        {
          e.skus = t.info;
          e.now_sku = t.info[0];
          e.nowprice = t.info[0].price;
          a.setData(e);
        }
        
      } else {
        core.alert(t.msg)
      }
    }, true)
  },

  /**
* 下拉刷新
*/
  onPullDownRefresh: function () {
    this.getinfo();
    wx.stopPullDownRefresh();
  },

  /**
   *上拉加载
   */
  onReachBottom: function () {
    console.log('加载更多')
    this.data.loaded || this.getlist();
  },

  //分享
  onShareAppMessage: function () {
    var title = this.data.detail.title;
    var path = '/yb_shop/pages/paycontent/info/index?id=' + this.data.detail.id;
    return {
      title: title,
      path: path
    }
  },
})